import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QInputDialog,
                             QColorDialog, QFontDialog, QFileDialog,
                             QPushButton, QToolTip)
from PyQt5.QtCore import QCoreApplication


btn_width, btn_height = 70, 30
win_width, win_height = 300, 400
n_row = 7
n_column = 3
start_x = 20
start_y = 20

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(100, 100, win_width, win_height)
        self.setWindowTitle('Dialog Test')

        list_func = [self.slot_QInputDialog, self.slot_QColorDialog, 
            self.slot_QFontDialog, self.slot_QFileDialog]
        for index in range(len(list_func)):
            i = int(index / n_column)
            j = index % n_column
            off_x = (win_width - start_x*2 - btn_width)/(n_column - 1)
            pos_x = start_x + off_x * j
            off_y = (win_height - start_y*2 - btn_height)/(n_row - 1)
            pos_y = start_y + off_y * i
            self.add_button((pos_x, pos_y), list_func[index])

        self.show()

    def add_button(self, position, function):
        name = function.__name__
        name = name.split('_')[1]

        btn = QPushButton(name, self)
        btn.resize(btn_width, btn_height)
        btn.move(*position)
        btn.clicked.connect(function)

    def slot_QInputDialog(self):
        text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
        if ok:
            print("Done --> ", text)

    def slot_QColorDialog(self):
        col = QColorDialog.getColor()
        if col.isValid():
            self.setStyleSheet("QWidget { background-color: %s }" % col.name())

    def slot_QFontDialog(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.lbl.setFont(font)

    def slot_QFileDialog(self):
        fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
        if fname[0]:
            f = open(fname[0], 'r')
            with f:
                data = f.read()
                self.textEdit.setText(data)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Example()
    sys.exit(app.exec_())
